package com.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;


public class HttpPostManager {
	
	/**
	 * Perform the HTTP post request with no parameters to the url
	 * @param url
	 * @return a string with the content of the response
	 */
	public static String doPostAndGetResponse(String url) {
		return HttpPostManager.doPostAndGetResponse(url, null);
	}
	
	/**
	 * Perform the HTTP post request to the url with the parameters params
	 * @param url
	 * @param params : parameters of the post request
	 * @return a string with the content of the response
	 */
	public static String doPostAndGetResponse(String url, List<? extends NameValuePair> params) { 
		return HttpPostManager.getStringResponse(HttpPostManager.doPost(url, params));
	}
	
	/**
	 * Perform a HTTP post request
	 * @param url
	 * @param params
	 * @return an InputStream with the response of the post
	 */
	public static InputStream doPost(String url, List<? extends NameValuePair> params) {
		InputStream is = null;
		
        try {
	         HttpClient httpclient = new DefaultHttpClient();
	         HttpPost httppost = new HttpPost(url);
	         // add the parameters to the requests if there are some
	         if (params != null)
	        	 httppost.setEntity(new UrlEncodedFormEntity(params));
	         HttpResponse response = httpclient.execute(httppost);
	         HttpEntity entity = response.getEntity();
	         is = entity.getContent();
        }
        catch(Exception e) {
        	e.printStackTrace();
        	Log.e("log_tag", "Error in http connection: "+e.toString());
        }
        
        return is;
	}
	
	/**
	 * Convert an InpuStream from a HTTP post response into a String
	 * @param is
	 * @return a string with the response
	 */
	public static String getStringResponse(InputStream is){
		StringBuilder sb = null;
		String result = null;
		
        try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			sb = new StringBuilder();
			sb.append(reader.readLine() + "\n");
			String line="0";
               
            while ((line = reader.readLine()) != null)
            	sb.append(line + "\n");
            
            is.close();
            result = sb.toString();
            
        }catch(Exception e){
        	
        	Log.e("log_tag", "Error converting result "+e.toString());
        }
        
        return result;
	}
}
